import dayjs from "dayjs";
import { getKeyList, downloadByUrl } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { getFileList, deleteFile } from "@/api/system";
import type { FileType } from "@/store/utils";
import { hasAuth } from "@/router/utils";
import { addDialog } from "@/components/ReDialog";
import Wavesurfer from "@/components/wavesurfer/index.vue";
import VideoPlayer from "./video.vue";
import ViewPdf from "./pdf.vue";

// import { downloadFile } from "@/api/upload";

export function useSysFile(tableRef: Ref) {
  const form = reactive({
    name: "",
    ext: "",
    userName: "",
    createdAt: ""
  });
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "文件名称",
      prop: "name",
      cellRenderer: ({ row }) => (
        <el-link onClick={() => onDownload(row)}>{row.name}</el-link>
      )
    },
    {
      label: "上传用户",
      prop: "pureUser.userName"
    },
    {
      label: "文件类型",
      prop: "mimetype"
    },
    {
      label: "文件大小",
      prop: "size"
    },
    {
      label: "预览",
      slot: "preview"
    },
    {
      label: "上传时间",
      prop: "createdAt",
      minWidth: 180,
      formatter: ({ createdAt }) =>
        dayjs(createdAt).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      width: 100,
      slot: "operation",
      hide: !hasAuth("sys:file:delete")
    }
  ];
  function onSearch() {
    loading.value = true;
    getFileList({
      ...form,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    })
      .then(data => {
        dataList.value = data.list;
        pagination.total = data.total;
        pagination.pageSize = data.pageSize;
        pagination.currentPage = data.currentPage;
      })
      .finally(() => {
        loading.value = false;
      });
  }
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  /** 下载 */
  function onDownload(row: FileType) {
    downloadByUrl(row.download, row.name);
  }
  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel(row?: any) {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    let ids = getKeyList(curSelected, "id");
    if (row?.id) {
      ids = [row.id];
    }
    await deleteFile({ id: ids });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }
  /** 视频播放 */
  function onPreviewVideo(row: FileType) {
    addDialog({
      title: row.name,
      center: true,
      hideFooter: true,
      contentRenderer: () => VideoPlayer,
      props: {
        url: row.url
      }
    });
  }
  function onPreviewAudio(row: FileType) {
    addDialog({
      title: row.name,
      hideFooter: true,
      contentRenderer: () => Wavesurfer,
      props: {
        url: row.url
      }
    });
  }
  /** 预览pdf */
  function onPreviewPdf(row: FileType) {
    addDialog({
      title: row.name,
      hideFooter: true,
      top: "10vh",
      contentRenderer: () => ViewPdf,
      props: {
        url: row.url
      }
    });
  }
  onMounted(() => {
    onSearch();
  });
  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    onSearch,
    resetForm,
    onbatchDel,
    onPreviewPdf,
    onPreviewAudio,
    onPreviewVideo,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
